package com.cqupt.scanning.system.utils.communication;

import com.alibaba.fastjson.JSONObject;
import com.cqupt.scanning.handler.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Data: 2021/6/29 20:21
 * @Author: 宋宝梁
 */

@Component
@Slf4j
@ServerEndpoint("/scanning/uploadFile/communication/{username}")
public class WebSocketServer {

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    // 连接的用户名
    private String username = "";
    // 初始化建议
    private Suggestion suggestion = new Suggestion();

    public Suggestion getSuggestion() {
        return suggestion;
    }

    /**
     * 连接建立成功调用的方法
     **/
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        this.session = session;
        this.username = username;
        if(webSocketMap.containsKey(username)){
            webSocketMap.remove(username);
            webSocketMap.put(username, this);
        } else {
            webSocketMap.put(username, this);
            addOnlineCount(); // 在线数加1
        }

        log.info("用户连接:" + username + ",当前在线人数为:" + getOnlineCount());

        try {
            Message message = new Message();
            message.setCode(20000);
            message.setMessage("连接成功");
            message.setDataMapOfGait(null);
            message.setDataMapOfBalance(null);
            String msgStr = JSONObject.toJSONString(message);
            sendInfo("admin", msgStr);
        } catch (IOException e) {
            log.error("用户:" + username + ",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法(关闭浏览器窗口触发此方法，去往其他路由页面不触发)
     */
    @OnClose
    public void onClose() {
        log.info("连接断开");
        if(webSocketMap.containsKey(username)){
            webSocketMap.remove(username); // 从set中删除
            subOnlineCount();
        }
        log.info("用户退出:" + username + ",当前在线人数为:" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户:{},报文:{}", this.username, message);
        if(StringUtils.isNotBlank(message)){
            try {
                this.suggestion = JSONObject.parseObject(message, Suggestion.class);
            }catch (Exception e){
                e.printStackTrace();
                throw new MyException(20001, "报文数据格式错误");
            }
        }
    }

    /**
     * 错误调用的方法
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.username+",原因:"+error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 向指定用户发送消息
     */
    public static void sendInfo(String username, String message) throws IOException {
        log.info("发送消息到:" + username + "，报文:" + message);
        if(StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)){
            webSocketMap.get(username).sendMessage(message);
        } else {
            log.error("用户" + username + ",不在线！");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static synchronized ConcurrentHashMap<String, WebSocketServer> getWebSocketMap() {
        return webSocketMap;
    }
}
